package ha.web.client.servlet.manager;

import ha.web.server.exceptions.GameException;
import ha.web.server.exceptions.UserNotFoundException;
import ha.web.server.manager.GameMangerServerSide;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class GameManager
 */
@WebServlet("/GameManager")
public class GameManager extends HttpServlet {

	private final int MY_TURN = 0 ;
	private final int CHAT = 1;
	private final int IN_GAME = 2;
	private final int MOVES = 3;
	private final int EMPTY = 4;
	private final int RESIGN = 5;
	private final int STATIS = 6;
	private final int UPDATE_BOARD= 7;
	/**
	 * 
	 */
	private static final long serialVersionUID = -291753338006723582L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GameManager() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// player tries to end his turn - check move - if ok - change turn and give other player control
		//check have user , moves
		GameMangerServerSide ins = GameMangerServerSide.getInstance();	
		PrintWriter out = response.getWriter();	
		int userId = -1;
		boolean cookieFound = false;
		Cookie[] userCookie = request.getCookies();
		for(int i=0; i<userCookie.length; i++) {
			if ("chinese_checkers".equals(userCookie[i].getName())) {
				String[] cookie = userCookie[i].getValue().split(":");
				userId = Integer.parseInt(cookie[1]);
				cookieFound = true;
			}
		}
		if(!cookieFound) {
			forwardToLogin(request,response,"cookieNotFound");
			return;
		}
		//Define request 
		int parm = EMPTY;
		if (request.getParameterMap().containsKey("my_turn"))
			parm = MY_TURN;
		else if (request.getParameterMap().containsKey("chat"))
			parm = CHAT;
		else if (request.getParameterMap().containsKey("in_game"))
			parm = IN_GAME;
		else if (request.getParameterMap().containsKey("moves"))
			parm = MOVES;
		else if (request.getParameterMap().containsKey("resign"))
			parm = RESIGN;
		else if (request.getParameterMap().containsKey("statistics"))
			parm = STATIS;
		else if (request.getParameterMap().containsKey("update_board"))
			parm = UPDATE_BOARD;
		
		String oldTable = null;
		String newTable = null;
		String  lastMov = null;
		//Handle request
		switch (parm) {
		case MY_TURN:
			try {
				String ans =  ins.isGameEnded(userId);
				if(ans!="") {
					out.print("turn$end_game$"+ans);
					break;
				}
				if (!ins.isMyTurn(userId)) {
					oldTable = ins.getPrevTable(userId);
					out.print("turn$false$"+oldTable);
					break;
				}
				oldTable = ins.getPrevTable(userId);
				newTable = ins.getTable(userId);
				lastMov = ins.getLastMove(userId);
				out.print("turn$true$"+oldTable+"$"+lastMov+"$"+newTable);
				break;
			}catch (UserNotFoundException e) {
				out.print(e.getMessage());
				break;
			}
		case CHAT:
			try {
				String newLine = request.getParameter("chat");
				ins.addLineToChat(userId, newLine);
				out.print("chat$"+ins.getChat(userId));
				break;
			}catch (UserNotFoundException e) {
				out.print(e.getMessage());
				break;
			}
		case IN_GAME:
			try {
				ins.getGameIdByUserId(userId);
				out.print("true");
				break;
			}catch (UserNotFoundException e) {
				out.print(e.getMessage());
				break;
			}
		case MOVES:
			String moves = request.getParameter("moves");
			try {
				oldTable = ins.getPrevTable(userId);
			} catch (UserNotFoundException e) {
				out.print(e.getMessage());
				break;
			}
			try {
				String his = ins.setLastMove(userId, moves);
				if(his!="") {
					out.print("move$game_ended$"+his);
					break;
				}
				newTable = ins.getTable(userId);
				out.print("move$turn_end$"+newTable);
				break;
			}catch (GameException e) {
				out.print("move$not_valid$"+e.getMessage()+"$"+oldTable);
				break;
			}
		case RESIGN:
			String his = "ERROR";
			try {
				oldTable = ins.getPrevTable(userId);
				his = ins.resignedGame(userId);
			} catch (UserNotFoundException e) {
				out.print(e.getMessage());
				break;
			}
			out.print("resi$"+oldTable+"$"+his+"$");
			break;
		case STATIS:
			String ans = "";
			try {
				 ans= ins.getStatistics(userId);
			} catch (UserNotFoundException e) {
				out.print("stat$false$"+oldTable);
				break;
			}
			out.print("stat$true$"+ans);
			break;
		case UPDATE_BOARD:
			try {
				newTable= ins.getTable(userId);
			} catch (UserNotFoundException e) {
				out.print("stat$false$"+oldTable);
				break;
			}
			out.print("upda$"+newTable);
			break;
		default:
			break;
		}
		return;

	}

	private void forwardToLogin(HttpServletRequest request, HttpServletResponse response, String string) throws ServletException, IOException {
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/Login");
		dispatcher.forward(request, response);	
		return;

	}
}
